<?php
namespace app\admin\controller;

use app\admin\model\Task as TaskModel;
//use app\admin\model\TaskType as TaskTypeModel;
use app\admin\model\DeviceGroup as DeviceGroupModel;
use app\admin\model\Account as AccountModel;
use app\admin\model\AccountGroup as AccountGroupModel;
use app\admin\model\Region as RegionModel;
use think\Db;
use think\Request;

class Task extends Base
{
    public function index()
    {
        $model = new TaskModel;
        
        //接收ajax传递的值
        $request = request();
        $ispost = $request->isPost();
        if($ispost){
            $id = $_POST["viewId"];
            $view = $model->getAll()->where("id",$id)->find();
            return json([
                'code' => 200,
                'view' => $view
            ]);
        }

       //$Tmodel = new TaskTypeModel;
        $Dmodel = new DeviceGroupModel;
        $Amodel = new AccountModel;
        $AGmodel = new AccountGroupModel;
        $Rmodel = new RegionModel;

        //渲染页面模板
        $model->field('t.id,t.name as tname,t.push_status,t.illustration as tillustration,t.begin_at,t.end_at,t.reward,t.status,t.content,t.partake_limit,t.lower_status,
        IFNULL(u.countid ,0) AS countid')/*y.name as yname,y.illustration as yillustration,*/
        ->alias('t')
           // ->join('task_type y','t.task_type_id = y.id ','left')
            //->join('task_user u','t.id = u.task_id','left')
            ->join('(SELECT task_id, COUNT(user_id) as countid from '. $this->dbTablePrefix .'task_user GROUP BY task_id HAVING task_id>0) u','t.id = u.task_id ','left')
            ->order('t.id','desc');
        // ->select();
        //->paginate(5);

        //搜索名称
        $phname = $this->request->param("phname");

        if(!empty($phname)){
            $model->where('t.name','like', '%'.$phname.'%');
        }
        $result = $model->paginate(10,false,[
            'query'=>['phname'=>$phname]
        ]);

        //计算总共记录条数
        $count = $result->total();
        //分页
        $page = $result->render();

        //渲染用户组
        //$Tmodel = $Tmodel->field('id,name')->select();
        $Dmodel = $Dmodel->field('id,name')->select();
        $Amodel = $Amodel->field('id,username')->select();
        $AGmodel = $AGmodel->field('id,name')->select();
        $Rmodel = $Rmodel->field('id,name')->select();

        $this->assign('currentPage',$result->currentPage());
        $this->assign('lastPage',$result->lastPage());
        $this->assign('page',$page);
        $this->assign('task',$result);
        //$this->assign('type',$Tmodel);
        $this->assign('devicegroup',$Dmodel);
        $this->assign('user',$Amodel);
        $this->assign('usergroup',$AGmodel);
        $this->assign('region',$Rmodel);
        $this->assign('count',$count);
        $this->assign('empty',"暂无数据");
        return $this->fetch();
    }

    public function create()
    {
        //接收ajax传递的值
        if($this->request->isPost()){
            $formdata = $this->request->post();
            $username = Db::query("select id,name from ". $this->dbTablePrefix ."user_group where `name`='".$formdata['name']."' and deleted_at is NULL ");

            if(!empty($username)){
                return json([
                    'code' => 4000,
                    'message'=>"用户名已存在"
                ]);
            }
            //计算时间差
            $formdata['need_time'] ="";
            $begin_at = strtotime($formdata['begin_at']);
            $end_at = strtotime($formdata['end_at']);
            $seconds = ceil($end_at-$begin_at);
            $days = floor($seconds/86400);
            if($days>0){
                $formdata['need_time'] .=  $days."天";
            }
            $hours = floor($seconds%86400/3600);
            if($hours>0){
                $formdata['need_time'] .=  $hours."小时";
            }
            $minutes = floor($seconds%3600/60);
            if($minutes>0){
                $formdata['need_time'] .=  $minutes."分钟";
            }

            $model = new TaskModel;
            $result = $model->allowField(true)->save($formdata);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //修改数据处理
    public function edit($id)
    {
        $model = new TaskModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();
        if($ispost){
            $formdata = $this->request->post();
            //计算时间差
            $formdata['need_time'] ="";
            $begin_at = strtotime($formdata['begin_at']);
            $end_at = strtotime($formdata['end_at']);
            $seconds = ceil($end_at-$begin_at);
            $days = floor($seconds/86400);
            if($days>0){
                $formdata['need_time'] .=  $days."天";
            }
            $hours = floor($seconds%86400/3600);
            if($hours>0){
                $formdata['need_time'] .=  $hours."小时";
            }
            $minutes = floor($seconds%3600/60);
            if($minutes>0){
                $formdata['need_time'] .=  $minutes."分钟";
            }

            $result = $model->allowField(true)->save($formdata,['id'=>$id]);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //删除单条记录
    public function delete($id)
    {
        //dump($id);exit;
        $result = TaskModel::update(['deleted_at'=>date('Y-m-d H:i:s')],['id'=>$id]);//软删除

        if($result){
            return json([
                'code' => 200,
            ]);
        }

    }

    //批量删除
    public function deleteArr()
    {
        $ispost = $this->request->isPost();
        if ($ispost) {
            $idArr = $this->request->post();

            $result = TaskModel::where('id','exp','in('.implode(',',$idArr['id']).')')->update(['deleted_at'=>date('Y-m-d H:i:s')]);//软删除

            if($result){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //下发任务
    public function lower($id)
    {
        $model = new TaskModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();

        if($ispost){
            $formdata = $this->request->post();
            if($formdata["lower_status"]==1){
                unset($formdata["lower_at"]);
            }

            $result = $model->allowField(true)->save($formdata,['id'=>$id]);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    //开关
    public function close($id)
    {
        $model = new TaskModel;
        //接收ajax传递的值
        $ispost = $this->request->isPost();

        if($ispost){
            $formdata = $this->request->post();

            $result = $model->allowField(true)->save($formdata,['id'=>$id]);

            if($result == 1){
                return json([
                    'code' => 200,
                ]);
            }

        }
    }

    public function jpush($id)
    {
        try {
            $model = new TaskModel;
            $app_key = "633f085eb5564a4a5217ed0e";
            $master_secret = "3741cee06bc58fc210826603";
            $client = new \JPush\Client($app_key, $master_secret);
            $options = array(
                'apns_production' => True
            );
            //$client = new JPush($app_key, $master_secret);
            $pusher = $client->push();
            $pusher->setPlatform('all');
            $pusher->addAllAudience();
            $pusher->setNotificationAlert('您有一条新的任务');
            $pusher->options($options);
            $response = $pusher->send();

            //创建定时任务
            /*$payload = $client->push()
                ->setPlatform("all")
                ->addAllAudience()
                ->setNotificationAlert("Hi, 这是一条定时发送的消息")
                ->build();*/
            // 创建一个2016-12-22 13:45:00触发的定时任务
            //$response1 = $client->schedule()->createSingleSchedule("每天14点发送的定时任务", $payload, array("time"=>"2019-03-28 13:35:00"));
            //print_r($response1);
            // 创建一个每天14点发送的定时任务
            /*$response2 = $client->schedule()->createPeriodicalSchedule("每天14点发送的定时任务", $payload,
                array(
                    "start"=>"2019-03-28 13:35:00",
                    "end"=>"2019-04-01 13:35:00",
                    "time"=>"14:00:00",
                    "time_unit"=>"DAY",
                    "frequency"=>1
                ));*/
            //print_r($response2);
            if($response) {
                $model->allowField(true)->save(['push_status'=>1],['id'=>$id]);
                return json([
                    'code' => 200,
                ]);
            }
        } catch (\Exception $e) {
            return $this->error('推送失败');
        }
    }
}